﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.DependencyInjection;

namespace StyleMVVM.Data
{
	[ExportPriority(-1)]
	[Export(typeof(IDataAccessSerializer))]
	public class DataAccessSerializer : IDataAccessSerializer
	{
		public string Serialize(object objectToSerialize)
		{
			DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());

			using (MemoryStream memoryStream = new MemoryStream())
			{
				serializer.WriteObject(memoryStream, objectToSerialize);

				byte[] bytes = memoryStream.ToArray();

				return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
			}
		}

		public object Deserialize(string objectString, Type objectType)
		{
			DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectType);

			using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(objectString)))
			{
				return serializer.ReadObject(memoryStream);
			}
		}
	}
}